package tq.com.tqstudent.ui.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.flyco.tablayout.SlidingTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.google.gson.Gson;
import com.lib.common.base.BaseFragment;
import com.lib.common.utils.LogUtil;
import com.lib.common.utils.SPUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.Subscribe;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import tq.com.tqstudent.App;
import tq.com.tqstudent.Constants;
import tq.com.tqstudent.R;
import tq.com.tqstudent.bean.BaseBean;
import tq.com.tqstudent.bean.IndexBean;
import tq.com.tqstudent.bean.SubjectBean;
import tq.com.tqstudent.bean.UserInfo;
import tq.com.tqstudent.bean.VisitorBean;
import tq.com.tqstudent.bean.event.ClassActivateEvent;
import tq.com.tqstudent.bean.event.SwitchEvent;
import tq.com.tqstudent.bean.params.PushParams;
import tq.com.tqstudent.net.ok.DialogCallback;
import tq.com.tqstudent.net.ok.StringCallback;
import tq.com.tqstudent.utils.VarietyUtil;
import tq.com.tqstudent.views.ClassHeadView;

/**
 * @Author rames
 * @date 2019/2/27 11:16
 */
public class ClassFragment extends BaseFragment implements OnTabSelectListener {
    @BindView(R.id.tabLayout)
    SlidingTabLayout tabLayout;
    @BindView(R.id.viewpager)
    ViewPager viewPager;
    @BindView(R.id.name_tv)
    TextView nameTV;
    @BindView(R.id.class_tv)
    TextView classTV;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.class_headview)
    ClassHeadView headView;

    private String tabName = ""; // 激活回来后对应的tab名
    private int currentIndex = 0; // viewpager的当前index;
    private IndexBean bean;
    private MyPagerAdapter mAdapter;
    private ArrayList<Fragment> mFragments = new ArrayList<>();
    private ArrayList<String> mTitles = new ArrayList<>();
    private static int WHILE_GET_UNREAD_COUNT = 5*1000; //5秒钟轮询一次是否有私信的小红点

    @Override
    protected int setView() {
        return R.layout.fragment_class;
    }

    @Override
    protected void init(View view) {
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(false);

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                currentIndex = viewPager.getCurrentItem();
                getTKData();
            }
        });
    }

    private void setValue(){
        if(null == bean || null == bean.subject){
            showToast("数据获取出错");
            return;
        }

        mTitles.clear();
        mFragments.clear();
        for (int i = 0; i < bean.subject.size(); i++) {
            if(bean.subject.get(i).chapter.size() > 0) {
                mTitles.add(VarietyUtil.getSubjectName(bean.subject.get(i).subject.id));
                mFragments.add(ClassItemFragment.getInstance(bean.subject.get(i).subject.id, bean.subject.get(i)));
            }
        }

        if(null != bean.clazz) {
            nameTV.setText(bean.clazz.name);
            classTV.setText("("+bean.clazz.name_ext+")");
        } else {
            nameTV.setText("赢在会学");
            classTV.setText("(赢在会学)");
        }

        mAdapter = new MyPagerAdapter(getChildFragmentManager());
        viewPager.setAdapter(mAdapter);
        viewPager.setOffscreenPageLimit(mFragments.size());

        viewPager.setCurrentItem(currentIndex);
        // 如果是激活班卡过来的
        if(tabName.trim().length() > 0){
            for (int i = 0; i < mTitles.size(); i++) {
                if(tabName.equals(mTitles.get(i))){
                    viewPager.setCurrentItem(i);
                    break;
                }
            }
        }

        mAdapter.notifyDataSetChanged();
        tabLayout.setViewPager(viewPager);
        tabLayout.setOnTabSelectListener(this);
//        tabLayout.showDot(4);
//        tabLayout.showMsg(3, 5);
//        tabLayout.setMsgMargin(3, 0, 10);
//        MsgView rtv_2_3 = tabLayout.getMsgView(3);
//        if (rtv_2_3 != null) {
//            rtv_2_3.setBackgroundColor(Color.parseColor("#6D8FB0"));
//        }
//        tabLayout.showMsg(5, 5);
//        tabLayout.setMsgMargin(5, 0, 10);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
    }

    private boolean isLoad = true;
    @Override
    public void onResume() {
        super.onResume();
//        if (isVisible() && isLoad) {
//            LogUtil.e("onResume...");
//            if(!UserInfo.isLogin()) {
        if(null == bean || null == bean.subject) {
            refreshLayout.autoRefresh();
        } else {
            getTKData();
        }
//            } else {
//                getData();
//            }
//        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
//            LogUtil.e("onHiddenChanged...");
//            getTKData();
        }
    }

    /** 重新刷新数据 */
    public void refresh(){
//        getTKData();
        refreshLayout.autoRefresh();
    }

    @Subscribe
    public void onClassActivateEvent(ClassActivateEvent event){
        int subject = event.subject;
        tabName = VarietyUtil.getSubjectName(subject);
        getTKData();
    }

    /** 未登录情况下先调用此接口 */
    private void getTKData(){
        String url = "api/user/chktk";
        OkGo.<BaseBean<VisitorBean>>get(App.getHttpUrl(url))
                .tag(this)
                .execute(new DialogCallback<VisitorBean>(getActivity(), false) {
                    @Override
                    public void handleSuccess(VisitorBean data) {
                        if(!TextUtils.isEmpty(data.tk)){
                            UserInfo.setToken(data.tk);
                        }

                        getData();
                    }

                    @Override
                    public void handleFail(BaseBean body) {
                        super.handleFail(body);
                        refreshLayout.finishRefresh();
                    }
                });
    }

    // 得到针对于未读私信的数量
    private void getUnReadCount(){
        String url = "api/im/umc";
        OkGo.<String>get(App.getHttpUrl(url))
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try{
                            String object = new JSONObject(response.body()).getString("data");
                            int count = new JSONObject(object).getInt("msg_count");
                            headView.setMsgCountPoint(count);
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                        LogUtil.e("请求index: "+index+" | respone: "+response.body());
                        unReadHandler.sendEmptyMessageDelayed(0, WHILE_GET_UNREAD_COUNT);
                    }

                    @Override
                    public void onError(Response<String> response) {

                    }
                });
    }

    private int index = 0;
    private Handler unReadHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            index++;
            LogUtil.e(" 请求index: "+index);
//            unReadHandler.sendEmptyMessageDelayed(0, WHILE_GET_UNREAD_COUNT);
            getUnReadCount();
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();

        if(unReadHandler != null){
            unReadHandler.removeMessages(0);
            unReadHandler.removeCallbacksAndMessages(null);
        }
    }

    @Override
    public void onPause() {
        super.onPause();

        if(unReadHandler != null){
            unReadHandler.removeMessages(0);
            unReadHandler.removeCallbacksAndMessages(null);
        }
    }

    private void getData(){
        String url = "api/clz/index";
        OkGo.<BaseBean<IndexBean>>get(App.getHttpUrl(url))
                .tag(this)
                .execute(new DialogCallback<IndexBean>(getActivity(), false) {
                    @Override
                    public void handleSuccess(IndexBean data) {
                        currentIndex = viewPager.getCurrentItem();
                        refreshLayout.finishRefresh();
                        if(UserInfo.isLogin()) {
                            setPushIdTask();

//                            getUnReadCount();
                        }
                        mTitles.clear();
                        bean = data;
                        setValue();
                        isLoad = false;
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                        refreshLayout.finishRefresh();
                    }
                });
    }

    private void setPushIdTask(){
        String cid = SPUtils.getInstance(getActivity()).getString(Constants.ALI_PUSH_DEVICE_ID);
        if(cid == null || cid.length() < 1){
            return;
        }

        String url = "api/user/pushid";
        PushParams params = new PushParams();
        params.dev_type = "android";
        params.pushid = cid;

        String json = new Gson().toJson(params);
        OkGo.<String>post(App.getHttpUrl(url))
                .tag(this)
                .upJson(json)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                    }
                });
    }

    @Override
    public void onTabSelect(int position) {
    }

    @Override
    public void onTabReselect(int position) {

    }

    private class MyPagerAdapter extends FragmentStatePagerAdapter {
        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            if(mTitles != null && mTitles.size() > position){
                return mTitles.get(position);
            }else{
                return "";
            }
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }
    }
}
